<template>
	<view class="bg-grey pad20">
		<sb-back-icon />
		<scroll-view>
			<u-cell-group :title="defaultAddress.region" class="address-info bg-white radius16 pad20 shadow-line"
				:border="false">
				<u-cell-item center :title="defaultAddress.address || 'Select Address Please'" :border-bottom="false"
					:is-link="true" :label="defaultAddress.name + '   ' + defaultAddress.tel" ndex="index"
					@click="goAddress">
				</u-cell-item>
			</u-cell-group>
			<u-gap height="30" bgColor="#f4f8f9"></u-gap>
			<view class="bg-white radius16 pad20 shadow-line">
				<view class="order-info flex bg-white pad10" v-for="item in goodsInfo" :key="item.id">
					<sb-img :src="item.cover" w="150" shadow />
					<view class="padh20  flex1 flex flex-col j-s">
						<view class="title u-line-2">
							{{ item.goods.name }}
							{{ item.goods.name }}
							{{ item.goods.name }}
							{{ item.goods.name }}
						</view>
						<view class="relative flex a-c">
							<view>
								<view class="font24 c-d">
									<view v-for="spec in item.specJson" class="flex a-c">
										{{spec}}
									</view>
								</view>
								<sb-price-text :price='item.salePrice' />
							</view>
							<view class="absolute counter">
								<u-number-box :min="1" :size='24' v-model="count" @change="changeCount(item)" />
							</view>
						</view>
					</view>
				</view>
			</view>
			<u-gap height="30" bgColor="#f4f8f9"></u-gap>
			<u-cell-group :border="false" class="bg-white radius16 pad20 shadow-line">
				<u-cell-item title="商品金额" :arrow="false">
					<view slot="right-icon" class="w100 goods-price">
						￥{{ orderPrice.originalPrice }}
					</view>
				</u-cell-item>
				<u-cell-item title="优惠券" @click="
            $go2(
              `/pages/main/tabbar/mine/discount-coupon?id=${order.orderInfo[0].id}`
            )
          " :arrow="!discountCoupon.tk">
					<view v-if="discountCoupon.tk" slot="right-icon" class="w100 goods-price">
						已减免￥{{ orderPrice.reducePrice || "" }}元
					</view>
				</u-cell-item>
				<u-cell-item class="remark-cell" title="备注" :arrow="false" :clickable="false">
					<u-input type="textarea" slot="right-icon" v-model="remark" placeholder="请输入备注"
						:autosize="{ minHeight: 20 }"></u-input>
				</u-cell-item>
			</u-cell-group>
			<view class="submit-content bg-white footer flex j-s a-c w100 padh30">
				<view class="c-price flex a-c">
					<span>￥<span class="number font42">{{
              orderPrice.presentPrice
            }}</span></span>
				</view>
				<view class="submit-btn">
					<u-button type="error" shape="circle" @click="submitOrder">Confirm</u-button>
				</view>
			</view>
		</scroll-view>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import { mapState, mapMutations } from "vuex";
	import { getPreviewOrderDetail } from '@/service/order'
	import { getDefaultAddress } from '@/service/address'
	import _ from 'love-u'

	export default {
		onLoad({ skuId, count }) {
			this.skuId = skuId
			this.count = ~~count
		},
		onReady() {
			if (!this.$checkLogin()) return this.$redirect2Login();
			this.getOrderDetail();
		},
		data() {
			return {
				info: {
					state: 1,
				},
				count: 0,
				goodsInfo: [],
				defaultAddress: null,
				id: "",
				cata_id: 0,
				res: "",
				remark: "",
				discountCoupon: {},
				orderPrice: {
					originalPrice: 0,
					presentPrice: 0,
					reducePrice: 0,
				},
			};
		},
		computed: {
			...mapState(["order"]),
		},
		watch: {
			"discountCoupon.tk"() {
				this.setPrice();
			},
		},
		methods: {
			...mapMutations(["SET_ORDER_INFO", "SET_ADDRESS"]),
			setPrice() {
				//originalPrice  应付   reducePrice优惠  presentPrice  实付
				let { originalPrice, presentPrice, reducePrice } = this.orderPrice;
				originalPrice = this.order.orderInfo.reduce((total, item) => {
					total += item.price;
					return total;
				}, 0);
				if (this.discountCoupon.tk) {
					const tk = this.discountCoupon.tk;
					switch (tk.type) {
						case 1: //满减
							// let [goal, reduce] = tk.desc.split("-").map(parseFloat);
							// if (goal < price) throw "未满足优惠券使用条件";
							// tk_reduce = reduce;
							// break;
						case 2: //直减
							presentPrice =
								parseFloat(originalPrice) -
								parseFloat(this.discountCoupon.tk.reduce);
							break;
						case 3: //打折
							presentPrice = (parseFloat(tk.discount) / 10) * originalPrice;
					}
				} else {
					presentPrice = originalPrice;
				}
				presentPrice = presentPrice > 0 ? presentPrice : 0;
				reducePrice = (originalPrice - presentPrice).toFixed(2);
				this.orderPrice = { originalPrice, presentPrice, reducePrice };
				console.log(this.orderPrice);
			},
			goAddress() {
				// if (this.unPayed)
				this.$go2("/pages/main/address/list?fromOrder=1");
			},
			async submitOrder() {
				if (!this.defaultAddress.address) {
					this.$msg("请先添加收货信息");
					return;
				}
				console.log(this.defaultAddress);
				try {
					let { success, data } = await this.$postB("/order/add", {
						createdBy: this.defaultAddress.createdBy,
						remark: this.remark,
						originalPrice: this.orderPrice.originalPrice,
						presentPrice: this.orderPrice.presentPrice,
						reducePrice: this.orderPrice.reducePrice,
						receiver: this.defaultAddress.name,
						tel: this.defaultAddress.tel,
						address: this.defaultAddress.address,
						region: this.defaultAddress.region,
						ticketFlowId: this.discountCoupon?.id,
						skus: this.order.orderInfo.map((i) => {
							return { skuId: i.sku.id, count: i.count || i.sku.count };
						}),
					});
					console.log(this.order.orderInfo);
					if (data) this.orderId = data;
					if (success) {
						const fromCart = this.order.orderInfo.find((o) => o.fromCart);
						if (fromCart) {
							const fromCartList = this.order.orderInfo
								.filter((o) => o.fromCart)
								.map((m) => m.id);
							await this.$postB("/cart/del", {
								id: fromCartList,
							});
						}
						this.SET_ORDER_INFO([]);
						console.log(this.order.orderInfo);
						this.$go2(`./add-success?id=${data}`);
					} else this.$msg(data);
				} catch (e) {
					this.$refs.uToast.show({
						title: "订单提交失败",
						type: "error",
					});
				}
			},
			async getOrderDetail() {
				try{
					this.defaultAddress = await getDefaultAddress()
					let data = await getPreviewOrderDetail(this.skuId)
					data.forEach(r => {
						r.specJson = _.pairs(JSON.parse(r.specJson)).map(r => r[1])
					})
					
					this.goodsInfo = data
				}catch(e){
					//TODO handle the exception
				}
			},
			changeCount(item) {
				item.price = item.salePrice * this.count;
				this.setPrice();
			},
		},
	};
</script>

<style lang="scss" scoped>
	.counter {
		right: 10rpx;

	}


	.footer {
		position: fixed;
		bottom: 0;
		left: 0;

		.pay {
			background: #e2231a;
			border-radius: 40rpx;
			color: #fff;
		}
	}

	.submit-content {
		height: 100rpx;

		.submit-btn {
			width: 150rpx;
		}
	}

	.remark-cell {
		/deep/ .u-cell__value {
			flex: 0;
		}

		/deep/ .u-cell_right {
			margin-left: 20rpx;
			flex: 1;
		}

		.goods-price {
			text-align: right;
		}
	}
</style>
